#!/usr/bin/python3

import sys,os
def envadd():
    path=os.path.dirname(__file__)
    path1=os.path.split(path)[0]
    sys.path.append(path1)
    path2=os.path.split(path1)[0]
    sys.path.append(path2)
    for i in os.listdir(path2):
        sys.path.append((os.path.join(path2,i)))
envadd()







import Lpars,Lsql,Lsmtp, Llogging
import logging
from config import sites,UNSUBSCRIBE_TEMPLATE
from utils import to_base64,Errorhandler

log=logging.getLogger('bishop')

def site_constr(mod_id,mod_text,site):
    try:
        mod_id=Errorhandler(mod_id)
        mod_text=Errorhandler(mod_text)
        log.debug(' Starting parsing %s....' % site)
        noedit_content=[]
        edited_db=[]
        content=[]
        newstext=''
        newslist=mod_id()
        if not newslist:
            return
        for i in newslist:
            noedit_content.append(i)
        log.debug(' List from %s ready' % site)
        list_news_from_db=Lsql.select_db(site,'news')
        for i in  list_news_from_db:
            edited_db.append(i[0])
        log.debug(' List from db ready')
        for i in noedit_content:
            if i in edited_db:pass
            else:content.append(i)
        log.debug(' News from site>>> News from bishop_db')
        if len(content)>0:
            log.debug(' News to add is %s' % len(content))
            for k in content:
                text_news=mod_text(k)
                if text_news:
                    newstext+=text_news
                else:content.remove(k)
            newscontent=list(newstext.split('?/|/?'))[0:-1]
            log.debug(' News_text ready')
            for i in content:
                Lsql.insert_db(site,i,newscontent[0].replace('\'',''))
                newscontent=newscontent[1:]
            log.debug('\t insert %s news - ready' % len(content))
        else:
            log.debug('\tNot have news')
    except:
        log.exception("exception message")

def Create_mail_content():
    try:
        GLOBAL_TEXT_CAHSE={}
        defis='\n'+'-'*90+'\n'
        id_news=[]
        content_list=Lsql.select_db()
        if  len(content_list)==0:
            log.debug('\tNot have news to sending....')
            return
        for i in content_list:
            id_news.append(i[0])
            text=i[2]
            if text.__class__.__name__=='bytes':
                text=text.decode(errors='ignore')
            if i[1] in GLOBAL_TEXT_CAHSE:
                GLOBAL_TEXT_CAHSE[i[1]]+=text+defis
            else:
                GLOBAL_TEXT_CAHSE[i[1]]=text+defis
        log.debug('News for sending ready....')
        client_id=Lsql.GetIdUser()
        log.debug('Users to sending = %s' % len(client_id) )
        client_findcross={}
        for k in client_id:
            if k[1:] in client_findcross:
                client_findcross[k[1:]]+=[k[0]]
            else: client_findcross[k[1:]]=[k[0]]
        n=1
        for m in client_findcross.keys():
            message=''
            for k in m:
                if k=='on' and  sites[str(n)] in  GLOBAL_TEXT_CAHSE.keys():
                    message+=GLOBAL_TEXT_CAHSE[sites[str(n)]]
                    n+=1
                else:
                    n+=1
            n=1
            log.debug('message consist %s simvols, id=%s' %(len(message),client_findcross[m]))
            if len(message)>0:
                Send(message,client_findcross[m])
        for i in id_news:
            Lsql.update_db(i)
    except:
        log.exception("exception message")


def Send(message,user):
    sql=''
    for i in user:
        sql+=r"id='{0}' or ".format(i)
    sql=sql[0:-3]
    request=Lsql.GetUserEmail(sql)
    emails=[]
    for i in request:
        emails.append(i[0])
    indexuser=0
    for email in emails:
        try:
            user_to_ususcribe=to_base64(email+'!#@#!'+str(user[indexuser]))
            log.debug('Send message to %s' % email)
            mes_with_uns=message+UNSUBSCRIBE_TEMPLATE % user_to_ususcribe
            indexuser+=1
            Lsmtp.SendEmail(mes_with_uns,subject='News from Bishop',toad=email)
        except:
            log.exception("exception message")


def main():
    log.debug('Start working')
    count_site=len(sites.keys())
    i=1
    while i <= count_site:
        sourse="site_constr(Lpars.{0}_id,Lpars.{0}_text,'{0}')".format(sites[str(i)])
        exec(sourse)
        i+=1
    log.debug('Start create content to send')
    Create_mail_content()
    log.debug(' Work is over!!\n-----------------------------------------------\n')
main()

